//--lyc ：新建团队记录时 加个 字段：mySession_ids ：array 
const db = wx.cloud.database()
const _ = db.command;
const app = getApp()
const openid = app.globalData.openid;
var watcherOne = null;
var watcherTwo = null;
var sessionList = [];
var memberKey
var searchKey
Page({
  data: {
    banner: [{
      picUrl: '../../../images/banner_10.jpg'
    },
    {
      picUrl: '../../../images/banner_11.jpg'
    }, {
      picUrl: '../../../images/banner_13.jpg'
    }],
    puplist: false,
    active: "home",
    teamInfo: {},
    teamInfo2: {},
    managerInfo: {},
    isLogin: false,
    hasNewApplyProject:"",
    cycleText:"",
    sessions:[],
  },

   //切换 tabBar
   goPost()
   {
    wx.navigateTo({
      url: '../../Pub/PubTexPic/PubTexPic',
    })
   },
   onChange(event) {
     console.log('切换了tabBar')
    this.setData({
      active: event.detail
    });
    switch (event.detail) {
      case 'message':
        this.message();
        break;
      case 'home':
        this.home();
        break;
      case 'member':
        this.member();
        break;
      case 'me':
        this.me();
        break;
    }
  },
  goPubtask(){
   wx.navigateTo({
     url: '../../Pub/PubTask/PubTask',
   })
  },
  async home() {
    console.log("tabBar: home ")
    if (watcherOne != null){
      await watcherOne.close();
      watcherOne = null;   
    }
      
    if (watcherTwo != null){
       await watcherTwo.close();
       watcherTwo = null;
    }
     
  },
  async member() {
    console.log("tabBar: member ")
    if (watcherOne != null){
      await watcherOne.close();
      watcherOne = null;
    }
      
    if (watcherTwo != null){
       await watcherTwo.close();
       watcherTwo = null;
    }
  },
  async me() {
    console.log("tabBar: me ")
    if (watcherOne != null){
      await watcherOne.close();
      watcherOne = null;
    }
      
    if (watcherTwo != null){
       await watcherTwo.close();
       watcherTwo = null;
    }
  },
  //首页的方法
  goPlant(e){
    console.log(e)
     wx.navigateTo({
       url: '../../plant/plant?id='+e.currentTarget.dataset.id
     })
  },
  getmemberKey(e){
    console.log(e.detail)
    memberKey=e.detail
 },
 gomember(){
     wx.navigateTo({
       url: '../teammember/teammember?memberKey='+memberKey,
     })
 },
 getCycleText(){
  db.collection('cycleText')
  .get()
  .then(res=>{
    console.log("res",res)
    var i=0
    setInterval(() => {
     let cycleTextItem=res.data[i].text
     i=i+1
     if(i==3)
     i=0
     this.setData({
       cycleText:cycleTextItem
     })
 }, 5000)
       
})
},
getSearchKey(e){
  console.log(e.detail)
  searchKey=e.detail
},
goSearch(){
  wx.navigateTo({
    url: '../teamSearch/teamSearch?searchKey='+searchKey,
  })
},
  onClose(){
      this.setData({
        puplist:false
      })
  },
  pupup() {
    this.setData({
      puplist: true
    })
  },

  //***********这是一条分割线 */
  //团队页消息方法
  message() {
    console.log("tabBar : 消息");
    var that = this;
    //监听团队的 会话数组  （all_team.团队记录.mySession_ids)
    this.watchMySids();
  },
  //属于message,监听我的会话数组
  async watchMySids() {
    console.log("watchMysids,监听团队的会话数组");
    var that = this;
    //监听器一
    watcherOne = await
      db.collection("all_team")
        .where({
          _openid: openid
        })
        .watch({
          onChange: this.ChangeOne.bind(this),
          onError: this.watchError.bind(this)
        });
  },
  //属于message,监听一的回调,监听二在其中设置
  async ChangeOne(snapshot) {
    console.log('ChangeOne',snapshot.docChanges);//snapshot.docChanges【0】是集合all_team中的一条团队记录
    var that = this;
    //判断是否有该团队的记录
    if (snapshot.docChanges.length) {          
      //团队会话数组  
      const mySids = snapshot.docChanges[0].doc.mySession_ids;
      //赋值全局变量
      sessionList = mySids;
      //团队会话数组不为0
      if ((mySids.length != 0)) {
        //提取出会话号数组
        var sidsCode = mySids.map(function (e) { return e.session_id });
        //将前一个监听器删除
        if (watcherTwo != null) {
          await watcherTwo.close();
          watcherTwo = null;
          console.log('删除了前一个监听器二',watcherTwo);
        }
        //设置新的监听器二(监听所有会话记录)
        watcherTwo = await
          db.collection('chat_msg')
            .where({ session_id: _.in(sidsCode) })
            .watch({
              onChange: that.ChangeTwo.bind(that),
              onError:  that.watchError.bind(that)
            });
      }
    }
    else{
      wx.showToast({
        title: '该账号不是团队账号',
        icon:'error'
      })
    }
  },
  //属于message,监听二的回调
  ChangeTwo(snapshot) {
    var that = this;
    console.log('changetwo docChanges', snapshot.docChanges);
    //初始化：遍历所有会话  进来后更新：遍历变化了的会话记录
    snapshot.docChanges.forEach(g);
    //遍历函数
    function g(e, index) {
      var msg_set = e.doc.msg_set;//会话的消息数组
      var len = msg_set.length;
      var sid = e.doc.session_id;//会话号
      //处理不为空的会话（为空不显示在消息列表）
      if (len) {
        console.log("处理会话：" + sid);
        //找出团队会话数组 中 对应的会话
        let arrIndex = sessionList.findIndex(item => {
          return item.session_id=== sid;
        });
        //处理会话对象的unReadNum（未读消息）和 show（显示）
        if (arrIndex > -1) {
          //团队离开该会话的时间
          var leaveTimeST = sessionList[arrIndex].leaveTimeST;
          //如果用户咨询后团队从未进入会话页
          if (sessionList[arrIndex].leaveTime == '') {
            sessionList[arrIndex].unReadNum = len;
          }else if(msg_set[len-1].createTimeStamp < leaveTimeST){
            sessionList[arrIndex].unReadNum = 0;
          }else{
            sessionList[arrIndex].unReadNum = function () {
              for (var x = 0; x < len; x++) {
                if ((msg_set[x].createTimeStamp > leaveTimeST) || (msg_set[x].createTimeStamp == leaveTimeST)) {
                  return len - x;
                }
              }
            }();
          }
          sessionList[arrIndex].show = true;
        }
      }
      else { return }
    }
    this.setData({
      sessions: sessionList
    })
  },
  //属于message,进入会话页
  async enterSession(e) {
    console.log('从消息列表页进入会话页');
    var sid = e.currentTarget.dataset.sid;
    var head = e.currentTarget.dataset.head;
    if(watcherOne!=null){
      await watcherOne.close();
      watcherOne = null;
    }
    if(watcherTwo!=null){
      await watcherTwo.close();
      watcherTwo = null;
    }
    await wx.navigateTo({
      url: '/pages/chatManager/chatManager?session_id=' + sid + '&hisUserInfo=' + head,
    })
  },
  //监听失败回调
  async watchError(err){
    console.log("onError", err);
    const res=await wx.showModal({
      title: '提示',
      content: '数据监听失败',
      showCancel:false,
      confirmText:'重新加载',
    })
    if(res.confirm) {
        if(watcherOne!=null){
          await watcherOne.close();
          watcherOne = null;
        }
        if(watcherTwo!=null){
          await watcherTwo.close();
          watcherTwo = null;
        }
        this.message();
    }   
  },
  ////////////*******这是一条分割线 */
//团队页我的---方法
  historyAct() {
    wx.navigateTo({
      url: '../historyAct/historyAct',
    })
  },
  doingAct() {
    wx.navigateTo({
      url: '../doingAct/doingAct',
    })
  },
  actAdmit() {
    wx.navigateTo({
      url: '../actAdmit_1/actAdmit_1',
    })
  },
  memeberAdmit() {
    wx.navigateTo({
      url: '../memeberAdmit/memeberAdmit',
    })
  },
  apply() {
    wx.navigateTo({
      url: '../actApply/actApply',
    })
  },

  //获取该团队的成员
  getMembers(){
    console.log("获取组织成员",app.globalData)
    db.collection("all_team").where({
      _openid:app.globalData.openid
    }).get()
    .then(res=>{
      this.setData({
        memberList:res.data[0].memberAdmit
      })
      console.log("11获取该组织成员列表成功",res)
    }).catch(err=>{
      console.log("11获取该组织成员列表失败",err)
    })
  },
  goMemberDetail(e){
    console.log("eeee",e)
    wx.navigateTo({
      url: '../../memberDetail/memberDetail?id='+e.currentTarget.dataset.memid,
    })
  },
  //获取该团队已截止的活动
  getEndProject() {
    let nowStamp = Date.parse(new Date())
    console.log("用户的openid(用于获取历史活动)", app.globalData.userInfo._openid)
    wx.cloud.callFunction({
      name: "getProjectList",
      data: {
        flag: "endProject",
        nowStamp: nowStamp,
        managerOpenid: app.globalData.userInfo._openid
      }
    }).then(res => {
      console.log("获取该组织历史活动成功", res)
      this.setData({
        endProject: res.result.data,
        endProjectLength: res.result.data.length
      })
      console.log("end", this.data.endProject)
    }).catch(err => {
      console.log("获取该组织历史活动失败", err)
    })
  },
  //获取该团队正在进行中的活动
  getIngProject() {
    let nowStamp = Date.parse(new Date())
    wx.cloud.callFunction({
      name: "getProjectList",
      data: {
        flag: "ingProject",
        nowStamp: nowStamp,
        managerOpenid: app.globalData.userInfo._openid
      }
    }).then(res => {
      console.log("获取该组织正在进行活动成功", res)
      this.setData({
        ingProject: res.result.data,
        ingProjectLength: res.result.data.length
      })
      console.log("ing", this.data.ingProject)

    }).catch(err => {
      console.log("获取该组织正在进行活动失败", err)
    })
  },
  goTeamEndProject() {
    let endProject = JSON.stringify(this.data.endProject)
    wx.navigateTo({
      url: '../teamProject/teamProject?project=' + endProject,
    })
  },
  goTeamIngProject() {
    let ingProject = JSON.stringify(this.data.ingProject)
    wx.navigateTo({
      url: '../teamProject/teamProject?project=' + ingProject,
    })
  },
  //获取待录取列表不为空的项目
  getHasSbAdmitProjectList() {
    const com = db.command
    db.collection('project')
      .where({
        teamOpenid: app.globalData.openid,
        vlnListNotAdmit: com.neq([])
      })
      .get()
      .then(res => {
        console.log("获取该团队待录取列表不为空的项目", res)
        this.setData({
          hasNewApplyProject:res.data
        })
      })
  },
  //获取待录取《进入团队》的志愿者列表
  getMemberNotAdmit(){
    db.collection("all_team").where({
      _openid: app.globalData.openid
    }).get()
    .then(res=>{
      console.log("获取待录取进入团队的志愿者列表成功啦",res.data[0].memberNotAdmit)
      this.setData({
        memberNotAdmit:res.data[0].memberNotAdmit
      })
    }).catch(err=>{
      console.log("获取待录取进入团队的志愿者列表失败",err)
    })
  },
  enterTeamAdmit(){
    wx.navigateTo({
      url: '../teamMemberAdmit/teamMemberAdmit' 
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getTeamInfo()
  {
    db.collection("all_team").where({
      _openid: app.globalData.openid
    }).get()
    .then(res=>{
      console.log("获取团队信息成功",res.data[0])
      this.setData({
       teamInfo:res.data[0]
      })
    }).catch(err=>{
      console.log("获取待录取进入团队的志愿者列表失败",err)
    })
  },
  onLoad: function (options) {
    app.editTabbar()
    console.log("传入团队页的teaminfo", app.globalData.teamInfo)
    this.getTeamInfo()
    this.getEndProject()
    this.getIngProject()
    this.getCycleText()
    this.getHasSbAdmitProjectList()
    // var pinyinjs = require('../../../utils/pinyin');
    // console.log("1111",pinyinjs["里"].join('，'))
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  enterTeamAdmit() {
    wx.navigateTo({
      url: '../teamMemberAdmit/teamMemberAdmit'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.active == 'message' ){
      console.log('从会话页返回消息列表页')
      this.message();
    }
    this.getMemberNotAdmit()
    this.getMembers()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("团队页隐藏");
    if (watcherOne != null){
      watcherOne.close();
      watcherOne = null;
    }
    if (watcherTwo != null){
      watcherTwo.close();
      watcherTwo = null;
    }    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("团队页卸载");
    if (watcherOne != null){
      watcherOne.close();
      watcherOne = null;
    }
    if (watcherTwo != null){
      watcherTwo.close();
      watcherTwo = null;
    }
    app.editTabbar()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
})
